﻿using CCWin;
using SqlBuilder.Code;
using SqlBuilder.Model;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Linq;
namespace SqlBuilder
{
    public partial class EditSqlTempLate : Skin_Metro
    {
        private string _id = string.Empty;
        //private Dictionary<string, int> _Map = new Dictionary<string, int>();
        public event Action<bool> completeEvent = null;
        public EditSqlTempLate(string id)
        {
            InitializeComponent();
            this._id = id;
            //this.TextBox_SqlTempTxt.SkinTxt.DoubleClick += SkinTxt_DoubleClick;
            this.TextBox_SqlTempTxt.SkinTxt.TextChanged += SkinTxt_DoubleClick;
            this.TextBox_SqlTempTxt.SkinTxt.KeyDown += EditSqlTempLate_KeyDown;
            this.TextBox_SqlTempTxt.SkinTxt.ScrollBars = ScrollBars.Vertical;

            this.TextBox_TempName.SkinTxt.KeyDown += EditSqlTempLate_KeyDown;
            this.DataG_SqlMap.KeyDown += EditSqlTempLate_KeyDown;
            this.KeyDown += EditSqlTempLate_KeyDown;
        }

        private void skinButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void EditSqlTempLate_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this._id))
            {
                LoadTempInfo(this._id);
            }
        }

        private void Button_SaveTempLate_Click(object sender, EventArgs e)
        {
            SaveTemp(true);
        }

        private void SaveTemp(bool isshowdialog)
        {
            if (string.IsNullOrEmpty(this.TextBox_TempName.Text))
            {
                MessageBoxEx.Show("请输入模板标签", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrEmpty(this.TextBox_SqlTempTxt.Text))
            {
                MessageBoxEx.Show("请输入SQL模板", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            this.BeginInvoke(new Action(() =>
            {
                Loading.ShowLayer(this, new Action(() =>
                {
                    MTempAllInfo info = new MTempAllInfo() { SQLMap = new List<MSQLMap>(), SQLTemplate = new MSQLTemplate() };
                    info.SQLTemplate.name = this.TextBox_TempName.Text;
                    info.SQLTemplate.template = this.TextBox_SqlTempTxt.Text;
                    info.SQLTemplate.id = this._id;
                    string excelindex = string.Empty;
                    int excelindexint = 0;
                    object cellvalue = string.Empty;

                    foreach (DataGridViewRow item in this.DataG_SqlMap.Rows)
                    {
                        excelindex = item.Cells["excelIndex"].Value.ToString();
                        if (!int.TryParse(excelindex, out excelindexint))
                        {
                            MessageBoxEx.Show(item.Cells["tempStr"].Value.ToString() + "列索引格式不正确", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        MSQLMap tempmap = new MSQLMap()
                        {
                            excelIndex = excelindex,
                            templateId = this._id,
                        };

                        cellvalue = item.Cells["sqlmapid"].Value;
                        tempmap.id = cellvalue != null ? cellvalue.ToString() : string.Empty;

                        cellvalue = item.Cells["tempStr"].Value;
                        tempmap.template = cellvalue != null ? cellvalue.ToString() : string.Empty;

                        cellvalue = item.Cells["script"].Value;
                        tempmap.script = cellvalue != null ? cellvalue.ToString() : string.Empty;
                        info.SQLMap.Add(tempmap);
                    }

                    string id = SqlBuilderService.Save(info);
                    string msg = "保存成功";
                    if (!string.IsNullOrEmpty(id))
                    {
                        this._id = id;
                        LoadTempInfo(this._id);
                    }
                    else
                    {
                        msg = "保存失败";
                    }

                    if (isshowdialog)
                    {
                        MessageBoxEx.Show(msg, "温馨提示");
                    }

                    if (completeEvent != null)
                    {
                        completeEvent(!string.IsNullOrEmpty(id));
                    }

                }));
            }));

        }

        private void LoadTempInfo(string id)
        {
            MTempAllInfo model = SqlBuilderService.QueryAllInfo(id);
            this.DataG_SqlMap.Rows.Clear();
            if (model != null)
            {
                this.TextBox_TempName.Text = model.SQLTemplate.name;
                if (model.SQLMap != null)
                {
                    int rowindex = 0;
                    foreach (MSQLMap item in model.SQLMap)
                    {
                        rowindex = this.DataG_SqlMap.Rows.Add();
                        this.DataG_SqlMap.Rows[rowindex].Cells["sqlmapid"].Value = item.id;
                        this.DataG_SqlMap.Rows[rowindex].Cells["tempStr"].Value = item.template;
                        this.DataG_SqlMap.Rows[rowindex].Cells["excelIndex"].Value = item.excelIndex;
                        this.DataG_SqlMap.Rows[rowindex].Cells["script"].Value = item.script;
                        //_Map.Add(item.template, rowindex);
                    }
                }

                this.TextBox_SqlTempTxt.Text = model.SQLTemplate.template;
            }
        }

        string _reg = "(?<template>【.*?】)";

        private void SkinTxt_DoubleClick(object sender, EventArgs e)
        {
            LoadTempsDataG();
        }

        private void LoadTempsDataG()
        {
            Regex reg = new Regex(_reg);
            string sqltemp = this.TextBox_SqlTempTxt.Text;
            //_Map.Clear();
            this.DataG_SqlMap.Rows.Clear();
            MTempAllInfo aainfo = SqlBuilderService.QueryAllInfo(this._id);
            MSQLMap nowmap = null;
            if (reg.IsMatch(sqltemp))
            {
                int rowindex = 0;
                List<string> temps = reg.Matches(sqltemp).Cast<Match>().Select(x => x.Groups["template"].Value).Distinct().ToList();
                foreach (string item in temps)
                {
                    rowindex = this.DataG_SqlMap.Rows.Add();
                    nowmap = GetTempMap(aainfo.SQLMap, item, rowindex);
                    this.DataG_SqlMap.Rows[rowindex].Cells["sqlmapid"].Value = string.Empty;
                    this.DataG_SqlMap.Rows[rowindex].Cells["tempStr"].Value = item;
                    this.DataG_SqlMap.Rows[rowindex].Cells["excelIndex"].Value = nowmap.excelIndex;
                    this.DataG_SqlMap.Rows[rowindex].Cells["script"].Value = nowmap.script;
                    //_Map.Add(template, rowindex);
                }
            }
        }

        private MSQLMap GetTempMap(List<MSQLMap> maps, string template, int rowindex)
        {
            MSQLMap temp = new MSQLMap()
            {
                excelIndex = rowindex.ToString(),
                id = string.Empty,
                script = string.Empty,
                template = template,
                templateId = this._id
            };

            if (maps == null || maps.Count == 0)
            {
                return temp;
            }

            MSQLMap now = maps.FirstOrDefault(x => x.template == template);
            if (now == null)
            {
                return temp;
            }

            return now;
        }

        private void DataG_SqlMap_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }

            if (e.ColumnIndex != 3)
            {
                return;
            }

            if (string.IsNullOrEmpty(this.TextBox_TempName.Text))
            {
                MessageBoxEx.Show("请输入模板标签", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrEmpty(this.TextBox_SqlTempTxt.Text))
            {
                MessageBoxEx.Show("请输入SQL模板", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            object script = this.DataG_SqlMap.Rows[e.RowIndex].Cells[3].Value;

            ScriptForm form = new ScriptForm(e.RowIndex, script == null ? string.Empty : script.ToString());
            form.SaveScriptEvent += Form_SaveScriptEvent;
            form.ShowDialog(this);
        }

        private bool Form_SaveScriptEvent(object arg1, string arg2)
        {
            this.DataG_SqlMap.Rows[Convert.ToInt32(arg1)].Cells[3].Value = arg2;
            SaveTemp(false);
            return true;
        }

        private void EditSqlTempLate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.S)
            {
                SaveTemp(true);
            }

            if (e.Control && e.KeyCode == Keys.A)
            {
                this.TextBox_SqlTempTxt.SkinTxt.SelectAll();
            }
        }
    }
}
